package com.air.repo.design.pattern.singleton;

import com.air.repo.design.pattern.singleton.Singleton4;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * 这里攻击Singleton4这个静态内部类
 *
 * @author yh 2018/7/12 20:19
 * @since: Jdk 1.8
 */
public class SingletonAttack {

    static void reflectAttack() throws Exception {
        Class classType = Singleton4.class;
        Constructor<?> c = classType.getDeclaredConstructor(null);
        c.setAccessible(true);

        Singleton4 e = (Singleton4) c.newInstance();
        Singleton4 c1 = Singleton4.getInstance();

        System.out.println(Singleton4.getInstance().hashCode());

        System.out.println(e.hashCode());
        System.out.println(c1.hashCode());
    }

    static void serializableAttack() throws Exception  {
        Singleton5 s5=Singleton5.getInstance();

        //写到文件
        FileOutputStream fos=new FileOutputStream("object.out");
        ObjectOutputStream oos =new ObjectOutputStream(fos);
        oos.writeObject(s5);
        oos.close();
        fos.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.out"));
        // 如果对象定义了readResolve()方法，readObject()会调用readResolve()方法。从而解决反序列化的漏洞
        Singleton5 s6=(Singleton5) ois.readObject();
        ois.close();

        System.out.println(s5.hashCode());
        System.out.println(s6.hashCode());


    }


    public static void main(String[] args) throws Exception {
//        reflectAttack();
        serializableAttack();

    }


}
